﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Wechat.Util.StateCode;

namespace Wechat.Util.ReturnMessage
{
    public class ResultMessage
    {
        #region 属性

        /// <summary>
        /// 请求是否成功
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public bool? Status { get; set; }


        /// <summary>
        /// 错误码
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public int? Code { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string Message { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public object Data { get; set; }

        #endregion

        #region 构造函数
        public ResultMessage()
        { }

        public ResultMessage(bool status)
        {
            this.Status = status;
            this.Message = status ? "操作成功" : "操作失败";
        }

        public ResultMessage(bool status, int code, string msg)
        {
            this.Status = status;
            this.Message = msg;
            this.Code = code;
        }

        public ResultMessage(bool status, string msg, object obj)
        {
            this.Status = status;
            this.Message = msg;
            this.Data = obj;
        }

        #endregion

        /// <summary>
        /// 转HTTP响应结果
        /// </summary>
        public HttpResponseMessage ToResponseMessage()
        {
            ResultMessage msg = this;

            HttpResponseMessage httpRspMsg = new HttpResponseMessage(HttpStatusCode.OK);

            string json = JsonConvert.SerializeObject(msg);
            httpRspMsg.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(json)));

            httpRspMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpRspMsg.Content.Headers.ContentType.CharSet = "utf-8";

            return httpRspMsg;
        }
    }
}
